﻿using mozhi.smarterp.BasicData.TaxRates;
using mozhi.smarterp.BasicData.TaxRates.Repository;
using mozhi.smarterp.BasicData.TaxRates.Service;
using mozhi.smarterp.BasicData.Units;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData
{
    public class TaxRateAppService : BasicDataAppService, ITaxRateAppService
    {
        private ITaxRateRepository _repository;
        private TaxRateManager _manager;
        private IGuidGenerator _guidGenerator;

        public TaxRateAppService(ITaxRateRepository repository, TaxRateManager manager, IGuidGenerator guidGenerator)
        {
            this._repository = repository;
            this._manager = manager;
            _guidGenerator = guidGenerator;
        }

        public async Task<TaxRateDto> CreateAsync(TaxRateCreateDto input)
        {
            var unit = await _manager.CreateAsync(_guidGenerator.Create(), input.Code, input.Name, input.Rate, input.Activated);

            await _repository.InsertAsync(unit);

            return ObjectMapper.Map<TaxRate, TaxRateDto>(unit);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _repository.DeleteAsync(id);
        }

        public async Task<TaxRateDto> GetAsync(Guid id)
        {
            var unit = await _repository.GetAsync(id);

            return ObjectMapper.Map<TaxRate, TaxRateDto>(unit);
        }

        public async Task<PagedResultDto<TaxRateDto>> GetListAsync(PagedResultRequestDto filter)
        {
            var count = await _repository.GetCountAsync();

            var units = await _repository.GetPagedListAsync(filter.SkipCount, filter.MaxResultCount, "Code");

            return new PagedResultDto<TaxRateDto>()
            {
                TotalCount = count,
                Items = ObjectMapper.Map<List<TaxRate>, List<TaxRateDto>>(units)
            };
        }

        public async Task<TaxRateDto> UpdateAsync(TaxRateUpdateDto input)
        {
            var taxRate = await _manager.UpdateAsync(input.Id, input.Code, input.Name, input.Rate, input.Activated);

            await _repository.UpdateAsync(taxRate);

            return ObjectMapper.Map<TaxRate, TaxRateDto>(taxRate);
        }
    }
}
